<template>
    <div class="sho">
      <div class="apps">
        <span class="qus"> 已到达约定地点，请等待乘客上车 </span><br><br><br>

        <button class="butts" @click="xingc">行程信息</button>
        <hr>

      </div>
      <div id="containers"></div>
      <div class="shuju">
        <ul class="infinite-list" v-infinite-scroll="load" style="overflow:auto">
          <div class="didians" v-for="rider in list">
            <div class="phones">
              <span class="shuzis">{{ rider.phoneNumber.slice(-4) }}</span><br>
              <span class="weihaos">尾号</span>
            </div>
            <span>{{ rider.startingPoint }}</span><br>
            <span>{{ rider.terminal }}</span>
          </div>
        </ul>
        <a :href="'tel:'+400456123"><i class="el-icon-phone"></i></a>
      </div>
      <div class="groups">
        <button @click="handlePickup" class="jiedaos">接到乘客</button>
      </div>


      <el-dialog title="请询问乘客乘车码" :visible.sync="carcodeShow">
        <el-form>
          <el-form-item label="乘车码">
            <el-input v-model="carcode"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="carcodeShow = false">取 消</el-button>
          <el-button type="primary" @click="ccm">提 交</el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import axios from "axios";

window._AMapSecurityConfig = {
  // 安全密钥
  securityJsCode: "23a30393a855e07d2ba7621ac8e4e6d2",
};

export default {
  name: "HomeView",
  data() {
    return {
      //乘车码弹框（默认：未开启）
      carcodeShow: false,
      //乘车码
      carcode: "",
      list: {},
      // 地图实例
      map: null,
      // 标记点
      marker: "",
      // 地址逆解析
      geoCoder: null,
      // 搜索提示
      AutoComplete: null,
      //缩放控件
      ToolBar: null,
      //地图放大镜
      HawkEye: null,
      // 搜索关键字
      keywords: "",
      // 位置信息
      locationInfo: {
        lng: "116.397427",
        lat: "39.909302",
        address: '',
      },
      // 搜索节流阀
      loading: false,
      // 搜索提示信息
      options: [],
      id: "",
    };
  },
  created() {
    this.initMap();
    this.getListSync(); // 修改为调用同步获取列表的方法
    this.id = sessionStorage.getItem("id")
  },
  methods: {
    ccm(){
      this.$router.push("/destination")
    },
    // 新增函数用于添加地图控件
    addMapControls() {
      if (this.ToolBar) {
        this.map.addControl(this.ToolBar);
      }
      if (this.HawkEye) {
        this.map.addControl(this.HawkEye);
      }
      if (this.Geolocation) {
        this.map.addControl(this.Geolocation);
      }
      if (this.Scale) {
        this.map.addControl(this.Scale);
      }
    },
    // 接到乘客
    handlePickup() {
      this.carcodeShow = true;
      this.carcode = "";
    },
    // 根据手机号查询到司机id
    async findDriverByTel() {
      const tel = JSON.parse(localStorage.getItem('login'));
      const response = await axios.post('personal/personal/findByTel?tel=' + tel);
      this.driverInfo = response.data;
      console.log(this.driverInfo);
      return this.driverInfo;
    },
    async getListSync() {
      try {
        // 先获取司机信息
        const driverInfo = await this.findDriverByTel();
        // 再根据司机信息获取列表数据
        const response = await axios.get(`/jiedan/riderQueue/findAll3?id=${this.id}`);
        this.list = response.data;

        // 遍历列表数据，对每个rider.terminal地址进行标记点操作
        this.list.forEach((rider) => {
          this.addMarkerForAddress(rider.startingPoint);
        });

      } catch (error) {
        console.error("获取数据失败：", error);
        alert("获取行程相关数据失败，请稍后重试");
      }
    },
    addMarkerForAddress(address) {
      if (!this.geoCoder || !this.map) {
        return;
      }
      // 使用地址逆解析插件将地址转换为经纬度
      this.geoCoder.getLocation(address, (status, result) => {
        if (status === 'complete' && result && result.geocodes && result.geocodes.length > 0) {
          const {location} = result.geocodes[0];
          const lng = location.lng;
          const lat = location.lat;

          // 创建标记点对象并添加到地图
          const marker = new AMap.Marker({
            position: [lng, lat],
            map: this.map
          });

          this.map.add(marker);

          // 设置地图中心点为当前解析地址的坐标
          this.map.setCenter([lng, lat]);
        } else {
          console.error(`地址 ${address} 解析失败`);
        }
      });
    },
    reset() {
      this.keywords = '';
      this.form = {
        lng: "119.793098",
        lat: "31.91243",
        address: '',
      }
      // 清除点
      this.removeMarker();
      // 标记点
      this.setMapMarker();
    },
    initMap() {
      AMapLoader.load({
        // 你申请的Key
        key: "b17513b156700f5d461409278e81ffa7",
        version: "2.0",
        // 需要用到的插件
        plugins: ["AMap.Geocoder", "AMap.AutoComplete", "AMap.ToolBar", "AMap.HawkEye", "AMap.Geolocation", "AMap.Scale"],
      })
        .then((AMap) => {
          this.map = new AMap.Map("containers", {
            viewMode: "3D", //是否为3D地图模式
            zoom: 14, //初始化地图级别
            center: [this.locationInfo.lng, this.locationInfo.lat], //初始化地图中心点位置
          });
          //地址逆解析插件
          this.geoCoder = new AMap.Geocoder({
            city: "010", //城市设为北京，默认：“全国”
            radius: 1000, //范围，默认：500
          });
          // 搜索提示插件
          this.AutoComplete = new AMap.AutoComplete({city: "全国"});
          this.ToolBar = new AMap.ToolBar({
            position: {
              bottom: '210px',
              right: '35px'
            }
          });
          this.HawkEye = new AMap.HawkEye({
            position: {
              bottom: '110px',
              left: '35px'
            }
          });
          this.Geolocation = new AMap.Geolocation({
            position: {
              bottom: '20px',
              right: '20px'
            }
          });
          this.Scale = new AMap.Scale({
            position: {
              bottom: '20px',
              left: '20px'
            }
          });
          // 调用函数添加地图控件
          this.addMapControls();
          // 省略部分代码...
          // 清除点
          this.removeMarker();
          // 标记点
          // this.setMapMarker();
          //点击获取经纬度;
          this.map.on("click", (e) => {
            // 获取经纬度
            this.locationInfo.lng = e.lnglat.lng;
            this.locationInfo.lat = e.lnglat.lat;
            // 省略部分代码...
          });
        })
        .catch((err) => {
          console.error("地图加载失败：", err);
        });
    },
    // 标记点
    setMapMarker() {
      if (!this.map) {
        return;
      }
      // 创建标记点对象
      this.marker = new AMap.Marker({
        position: [this.locationInfo.lng, this.locationInfo.lat],
        map: this.map
      });
      // 逆解析地址
      this.toGeoCoder();
      this.map.add(this.marker);
    },
    // 清除点
    removeMarker() {
      if (this.marker) {
        this.map.remove(this.marker);
      }
    },
    xingc() {
      this.$router.push("/Trip")
    },
    // 逆解析地址
    toGeoCoder() {
      let lnglat = [this.form.lng, this.form.lat];
      this.geoCoder.getAddress(lnglat, (status, result) => {
        if (status === "complete") {
          this.form.address = result.regeocode.formattedAddress;
        } else {
          this.form.address = '';
        }
      });
    },
    querySearchAsync(queryString, cb) {
      if (queryString) {
        this.AutoComplete.search(queryString, (status, result) => {
          if (status === 'complete') {
            this.options = result.tips;
            for (let i = 0; i < this.options.length; i++) {
            }
          } else {
            this.options = [];
          }
          cb(this.options);
        });
      } else {
        this.options = [];
        cb(this.options);
      }
    },
    handleSelect(val) {
      // 清空时不执行后面代码
      if (!val) {
        return;
      }
      this.form = {
        lng: val.location.lng,
        lat: val.location.lat,
        address: '',
      };
      // 省略部分代码...
    },
  },
  mounted() {
  },
};
</script>

<style scoped>

#containers {
  width: 100%;
  height: 690px;
}

.sho {
  //width: 400px; //height: 100px; //margin-left: 10px; //float: left; //border-radius: 10px; //background-color: #ffffff;

  i {
    font-size: 40px;
    margin-top: 20px;
  }
}

.didians {
  width: 360px;
  height: 60px;

  span {
    line-height: 40px;
  }
}

ul {
  width: 200px;
  height: 100px;
  float: left;
}

.apps {
  height: 65px;
  width: 100%;
  background-color: #FFFFFF;
  float: left;
}

.qus {
  font-size: 18px;
  float: left;
  margin-top: 17px;
  margin-left: 10px;
}



.butts {
  //width: 80px; height: 30px; background-color: #52b7fd;
  color: #FFFFFF;
  border-radius: 5px;
  float: right;
  margin-top: -40px;
  margin-right: 10px;
  font-size: 12px;
}

.phones {
  width: 50px;
  height: 85px;
  float: left;
}

.shuzis {
  font-size: 15px;
}

.weihaos {
  font-size: 20px;
}

.groups {
  width: 100%;
  height: 80px;
  //background-color: #dedede; float: left; //margin-left: 10px;
}

.daoda {
  width: 180px;
  height: 40px;
  background-color: #ff6700;
  border-radius: 30px;
  border: 0px;
  color: #FFFFFF;
  margin-right: 20px;
}

.infinite-list {
  width: 88%;
}

.jiedaos {
  width: 100%;
  height: 70px;
  background-color: #00c7ff;
  //border-radius: 30px; border: 0px; color: #FFFFFF;
}
</style>
